/**
 * Copyright (c) 2020 lizebang
 *
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

package zap

import (
	"io"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var (
	ZapLogger *zapLogger
)

func init() {
	zap.NewProduction()
	encoder := zapcore.NewJSONEncoder(zapcore.EncoderConfig{
		TimeKey:       "ts",
		LevelKey:      "level",
		NameKey:       "logger",
		CallerKey:     "caller",
		MessageKey:    "msg",
		StacktraceKey: "stacktrace",
		LineEnding:    zapcore.DefaultLineEnding,
		EncodeLevel:   zapcore.CapitalLevelEncoder,
		EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString(t.In(time.FixedZone("CST", 8*3600)).Format(time.RFC3339Nano))
		},
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.FullCallerEncoder,
	})

	infoWriter := getWriter("info", ".log")
	errorWriter := getWriter("error", ".log")

	core := zapcore.NewTee(
		zapcore.NewCore(encoder, zapcore.AddSync(infoWriter), zap.NewAtomicLevelAt(zap.InfoLevel)),
		zapcore.NewCore(encoder, zapcore.AddSync(errorWriter), zap.NewAtomicLevelAt(zap.ErrorLevel)),
	)

	ZapLogger = &zapLogger{zap.New(core, zap.AddStacktrace(zap.ErrorLevel), zap.AddCaller(), zap.AddCallerSkip(1)).Sugar()}
}

func getWriter(filename, extension string) io.Writer {
	hook, err := rotatelogs.New(
		filename+"-%Y-%m-%d"+extension,
		rotatelogs.WithLinkName(filename+extension),
		rotatelogs.WithMaxAge(30*24*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	if err != nil {
		panic(err)
	}
	return hook
}
